<template>
  <div class="user-container">
    <div class="mb-4">
      <n-button :disabled="!userState.checkedRowKeys.length" type="error" @click="delUser(userState.checkedRowKeys)">
        删除选中
      </n-button>
    </div>
    <n-data-table size="large" :bordered="false" flex-height remote :checked-row-keys="userState.checkedRowKeys"
      :columns="userState.columns" :data="userState.data" :pagination="pagination" :row-key="row => row.id"
      @update:checked-row-keys="rows => userState.checkedRowKeys = rows" :loading="mainStore.pageLoading" :scroll-x="600">
      <template #empty>
        <n-empty description="暂无用户"></n-empty>
      </template>
    </n-data-table>
  </div>

  <BasicModal title="修改用户" to=".user-container" @confirm="editUser" @register="editUserModalRegister">
    <n-form ref="editUserFormRef" :model="userState.formData" size="large" label-placement="left" :rules="userState.rules"
      @keyup.enter="editUser">
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="userState.formData.username" :allow-input="noSideSpace" clearable placeholder="用户名"
          size="large" type="text" />
      </n-form-item>
      <n-form-item label="用户角色" path="role">
        <n-radio-group v-model:value="userState.formData.role">
          <n-radio value="admin">admin</n-radio>
          <n-radio value="user">user</n-radio>
        </n-radio-group>
      </n-form-item>
    </n-form>
  </BasicModal>
</template>

<script setup>
import { NSpace, NButton, NDescriptions, NDescriptionsItem, NTag, NIcon } from 'naive-ui'
import { defineAsyncComponent, h, getCurrentInstance, reactive } from 'vue'
import { userList, deleteUser, updateUser } from '@api/userApi'
import { useMainStore } from '@/store'
import { noSideSpace, timeFormat } from '@/utils'
import { useDialog } from '@/hook/popup/useDialog'
import { useModal } from '@c/Modal/useModal'
import { TrashOutline } from '@vicons/ionicons5'

const { proxy } = getCurrentInstance()
const BasicModal = defineAsyncComponent(() => import('@c/Modal/BasicModal.vue'))

const mainStore = useMainStore()

const userState = reactive({
  data: [],
  formData: {},
  rules: {
    username: { required: true, message: '用户名不能为空', trigger: 'input' }
  },
  checkedRowKeys: [],
  columns: [
    { type: 'selection' },
    {
      type: 'expand',
      renderExpand: row => {
        return h(NDescriptions, { columns: 1, labelPlacement: 'left' }, {
          default: () => [
            // h(NDescriptionsItem, { label: '邮箱' }, {
            //   default: () => h(NTag, { type: 'primary', size: 'small' },
            //       { default: () => row.email ? row.email : '暂无' }),
            // }),
            h(NDescriptionsItem, { label: '注册时间' }, {
              default: () => h(NTag, { type: 'primary', size: 'small' }, { default: () => timeFormat(row.createdAt) }),
            }),
            h(NDescriptionsItem, { label: '修改时间' }, {
              default: () => h(NTag, { type: 'primary', size: 'small' }, { default: () => timeFormat(row.updatedAt) }),
            }),
          ],
        })
      },
    },
    { title: 'id', key: 'id', minWidth: 80, width: 80 },
    { title: '用户名', key: 'username', minWidth: 100, width: 100 },
    {
      title: '身份', key: 'role', minWidth: 90, width: 90, render(row) {
        return h(NTag, { type: row.role === 'admin' ? 'info' : 'success' }, { default: () => row.role })
      },
    },
    {
      title: '操作', minWidth: 110, width: 110,
      render(row) {
        return h(NSpace, {}, {
          default: () => [
            h(NButton, {
              size: 'small',
              type: 'primary',
              onclick() {
                userState.formData = { ...row }
                openEditUserModal()
              },
            }, { default: () => '编辑' }),
            h(NButton, {
              size: 'small',
              type: 'error',
              onclick() {
                delUser([row.id])
              },
            }, { default: () => h(NIcon, { component: TrashOutline, size: 16 }, {}) }),
          ],
        })
      },
    },
  ],
})

const pagination = reactive({
  ...mainStore.pagination,
  onChange(page) {
    pagination.page = page
    getUserList()
  },
  onUpdatePageSize(pageSize) {
    pagination.page = 1
    pagination.pageSize = pageSize
    getUserList()
  },
})

const getUserList = async () => {
  try {
    mainStore.setPageLoading(true)
    const res = await userList({ page: pagination.page, limit: pagination.pageSize })
    if (res?.statusCode === 200) {
      userState.data = res.data.rows
      pagination.itemCount = res.data.count
    }
  } finally {
    mainStore.setPageLoading(false)
  }
}
getUserList()

const [
  editUserModalRegister, {
    openModal: openEditUserModal,
    closeModal: closeEditUserModal,
    setModalLoading: setEditUserModal,
  }] = useModal({
    positiveText: '修改',
  })

const editUser = () => {
  proxy.$refs.editUserFormRef.validate(async validate => {
    if (validate) return false
    try {
      setEditUserModal(true)
      const form = { ...userState.formData }
      const res = await updateUser(form)
      if (res?.statusCode !== 200) return false
      closeEditUserModal()
      $message.success(res.message)
      await getUserList()
    } finally {
      setEditUserModal(false)
    }
  })
}

const delUser = ids => {
  const delDialog = useDialog({
    title: '删除',
    content: `是否删除${userState.checkedRowKeys.length > 1 ? '这些' : '该'}用户?`,
    type: 'error',
    icon: true,
    async confirm() {
      const res = await deleteUser({ id: [...ids] })
      if (res?.statusCode === 200) {
        delDialog.destroy()
        userState.checkedRowKeys = []
        await getUserList()
        $message.success(res.message)
      }
    },
  })
}
</script>

<style lang="less" scoped></style>
